package com.assignwork.service.impl;

import com.assignwork.dto.StatisticsSearchDTO;
import com.assignwork.entity.VoyageVisa;
import com.assignwork.mapper.StatisticsMapper;
import com.assignwork.mapper.VoyageVisaMapper;
import com.assignwork.service.IStatisticsService;
import com.assignwork.util.PinyinUtil;
import com.assignwork.vo.*;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.AllArgsConstructor;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springblade.common.utils.OfficeExportUtil;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.DictBizCache;
import org.springblade.system.user.cache.UserCache;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@AllArgsConstructor
public class StatisticsServiceImpl extends BaseServiceImpl<VoyageVisaMapper, VoyageVisa> implements IStatisticsService {

    private StatisticsMapper statisticsQuery;
    private VoyageVisaServiceImpl service;

    @Override
    public List<StatisticsVO> shiftStatisticsList(StatisticsSearchDTO dto) {
        List<StatisticsVO> data = statisticsQuery.statisticsQuery(dto);
        return data;
    }
    @Override
    public IPage<ThroughPutStatisticsVO> throughPutList(StatisticsSearchDTO dto , IPage<ThroughPutStatisticsVO> ipage) {

        if(dto.getBERTHCOD()!=null && !dto.getBERTHCOD().isEmpty() ){
            if(dto.getBERTHCOD().length()==3 || dto.getBERTHCOD().equals("G21_SGS")){
                dto.setBERTHCOD(dto.getBERTHCOD().substring(0, 3));
            }
        }

        dto.setCargoTypeList(this.carSearchSpec(dto.getCargoType()));
        List<ThroughPutStatisticsVO> data = statisticsQuery.throughPutstatisticsQuery(dto,ipage);
         ThroughPutStatisticsVO sum= statisticsQuery.sumThroughPutstatisticsQuery(dto);
        data.forEach(item->{

            item.setImpExp(item.getImpExp().equals("I") ? "进口" : "出口");
            item.setTradeType(item.getTradeType().equals("1") ? "外贸" : "内贸");
            item.setPackageBulkKeyList(item.getPackageBulkKey());
            if(Func.isNotBlank(item.getSz())){
                item.setSz(item.getSz().equals("BULK") ? "散" : "杂");
            }
            item.setSumThroughPut(sum.getSumThroughPut());
            item.setBerthName(DictBizCache.getValue("ship_dynamics", item.getBerthCode()));

            if(item.getFromHuadong().equals("0")){
                item.setUpdateUserName(String.valueOf(UserCache.getUser(Long.parseLong(item.getUpdateUser())).getRealName()));
                item.setCreateUserName(String.valueOf(UserCache.getUser(Long.parseLong(item.getCreateUser())).getRealName()));
            }
        });
        for(int i=0;i< data.size();i++){
            for(int j=i+1;j<data.size();j++){
               if(data.get(i).getShipNameZh().equals(data.get(j).getShipNameZh()) &&data.get(i).getTotalTon().equals(data.get(j).getTotalTon())){
                   data.get(j).setImpExp("");data.get(j).setShipNameZh("");
                   data.get(j).setStatTime(null);data.get(j).setVoyage("");data.get(j).setBerthName("");data.get(j).setTradeType("");
                   data.get(j).setTotalTon("");data.get(j).setDeadWeightTon(null);data.get(j).setNetWeight(null);
               }else{
                   continue;
               }
            }
        }
        ipage.setTotal(sum.getTotalCount());
        return ipage.setRecords(data);
    }
    @DS("huadong")
    @Override
    public List<ThroughPutStatisticsVO> berthList() {
        return statisticsQuery.berthListQuery();
    }

    @Override
    public void exportthroughput(HttpServletResponse response, StatisticsSearchDTO dto) {
        if(dto.getBERTHCOD()!=null && !dto.getBERTHCOD().isEmpty() ){
            if(dto.getBERTHCOD().length()==3 || dto.getBERTHCOD().equals("G21_SGS")){
                dto.setBERTHCOD(dto.getBERTHCOD().substring(0, 3));
            }
        }
        dto.setCargoTypeList(this.carSearchSpec(dto.getCargoType()));
        List<ThroughPutStatisticsVO> data = statisticsQuery.noPageThroughPutstatisticsQuery(dto);
        data.forEach(item->{
            item.setImpExp(item.getImpExp().equals("I") ? "进口" : "出口");
            item.setTradeType(item.getTradeType().equals("1") ? "外贸" : "内贸");
            item.setPackageBulkKeyList(item.getPackageBulkKey());
            if(Func.isNotBlank(item.getPackageBulkKey())){
                item.setPackageBulkKey(item.getPackageBulkKey().equals("BULK") ? "散" : "杂");
            }
            item.setBerthName(DictBizCache.getValue("ship_dynamics", item.getBerthCode()));
            if(item.getFromHuadong().equals("0")){
                item.setUpdateUserName(String.valueOf(UserCache.getUser(Long.parseLong(item.getUpdateUser())).getRealName()));
                item.setCreateUserName(String.valueOf(UserCache.getUser(Long.parseLong(item.getCreateUser())).getRealName()));
            }

        });
        String title = "吞吐量查询列表";
        String fileName = "吞吐量查询列表";
        OfficeExportUtil.exportExcel(OfficeExportUtil.getWorkbook(title, "sheet1", ThroughPutStatisticsVO.class, data), fileName, response);
    }

    @Override
    public List<ThroughPutStatisticsVO> ttlhlList(StatisticsSearchDTO dto) {
        List<ThroughPutStatisticsVO> data = statisticsQuery.ttlhlQuery(dto);
        data.forEach(item-> {
                String zjf = PinyinUtil.getPinYinHeaderChar( item.getTtlhl()).toUpperCase();
                String name = item.getTtlhl() + '(' + zjf + ')';
                item.setTtlhlName(name);
        });
        return data;
    }
    @DS("huadong")
    @Override
    public List<ThroughPutStatisticsVO> hmlList() {
        List<ThroughPutStatisticsVO> data = statisticsQuery.hmQuery();
        data.forEach(item-> {
//            String zjf = PinyinUtil.getPinYinHeaderChar( item.getCARGOKINDNAM()).toUpperCase();
//            String name = item.getCARGOKINDNAM() + '(' + zjf + ')';
//            item.setCARGOKINDNAM(name);
        });
        return data;
    }

    @Override
    public void InUpTtlStat(BladeUser bladeUser, StatisticsSearchDTO dto) {
        if(dto.getId()==null) {
            VoyageVisa voyageVisa = new VoyageVisa();
            voyageVisa.setUpdateUser(bladeUser.getUserId());
            voyageVisa.setCreateUser(bladeUser.getUserId());
            voyageVisa.setCreateTime(new Date(System.currentTimeMillis()));
            voyageVisa.setUpdateTime(new Date(System.currentTimeMillis()));
            voyageVisa.setVisaTon(dto.getVisaTon());
            voyageVisa.setCreateDept(Long.parseLong(bladeUser.getDeptId()));
            voyageVisa.setIsSupplement(1);
            voyageVisa.setReCargoNameKey(dto.getCargoType());
            voyageVisa.setPackageBulkKey(dto.getPackageBulkKeyList());
            voyageVisa.setNetWeight(dto.getNetWeight());
            voyageVisa.setDeadWeightTon(dto.getDeadWeightTon());
            voyageVisa.setImpExp(dto.getImpExp().equals("进口") ? "I" : "E");
            voyageVisa.setStatTime(dto.getStatTime());
            voyageVisa.setBeginTime(dto.getBeginTime());
            voyageVisa.setEndTime(dto.getFinishTime());
            voyageVisa.setUnberthingTime(dto.getUnberthingTime());
            voyageVisa.setIsDeleted(0);
            voyageVisa.setStatus(1);
            StatisticsSearchDTO dto2 = new StatisticsSearchDTO();
            dto2.setShipNameZh(dto.getShipNameZh());
            dto2.setVoyage(dto.getVoyage());
            dto2.setImpExp(voyageVisa.getImpExp());
            voyageVisa.setVoyageId(statisticsQuery.voyageQuery(dto2));
            statisticsQuery.insert(voyageVisa);
        }else {
            LambdaUpdateWrapper<VoyageVisa> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(VoyageVisa::getVoyageId, Long.parseLong(dto.getVoyageId())).eq(VoyageVisa::getIsDeleted, 0);
            List<VoyageVisa> result = statisticsQuery.selectList(lambdaUpdateWrapper);

            LambdaUpdateWrapper<VoyageVisa> lambdaUpdateWrapper2 = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper2.eq(VoyageVisa::getId, Long.parseLong(dto.getId())).eq(VoyageVisa::getIsDeleted, 0);
            VoyageVisa result2 = statisticsQuery.selectOne(lambdaUpdateWrapper2);
            result2.setVisaTon(dto.getVisaTon());
            result2.setReCargoNameKey(dto.getReCargoNameKey());
            result2.setPackageBulkKey(dto.getPackageBulkKeyList());
            baseMapper.updateById(result2);
            for(VoyageVisa data:result) {
//                data.setUpdateTime(new Date(System.currentTimeMillis()));
//                data.setUpdateUser(bladeUser.getUserId());
//                data.setStatTime(dto.getStatTime());
//                data.setEndTime(dto.getFinishTime());
//                data.setBeginTime(dto.getBeginTime());
                Date date = dto.getUnberthingTime();
//                data.setUnberthingTime(date);
//                data.setNetWeight(dto.getNetWeight());
//                data.setDeadWeightTon(dto.getDeadWeightTon());
                LambdaUpdateWrapper<VoyageVisa> up = new LambdaUpdateWrapper<>();
                up.eq(VoyageVisa::getId, data.getId())
                        .set(VoyageVisa::getUpdateTime,new Date(System.currentTimeMillis()))
                        .set(VoyageVisa::getUpdateUser,bladeUser.getUserId())
                        .set(VoyageVisa::getStatTime,dto.getStatTime())
                        .set(VoyageVisa::getEndTime,dto.getFinishTime())
                        .set(VoyageVisa::getBeginTime,dto.getBeginTime())
                        .set(VoyageVisa::getUnberthingTime,date)
                        .set(VoyageVisa::getNetWeight,dto.getNetWeight())
                        .set(VoyageVisa::getDeadWeightTon,dto.getDeadWeightTon());
                service.update(new VoyageVisa(), up);


//                baseMapper.updateById(data);
            }

        }
    }

    @Override
    public List<ThroughPutStatisticsVO> selectVoyage(StatisticsSearchDTO dto) {
        List<ThroughPutStatisticsVO> data=statisticsQuery.selectVoyageSearch(dto);
        data.forEach(item -> {
            item.setImpExp(item.getImpExp().equals("I") ? "进口" : "出口");
            item.setTradeType(item.getTradeType().equals("1") ? "外贸" : "内贸");
            item.setPackageBulkKeyList(item.getPackageBulkKey());
            if (Func.isNotBlank(item.getSz())) {
                item.setSz(item.getSz().equals("BULK") ? "散" : "杂");
            }

            item.setBerthName(DictBizCache.getValue("ship_dynamics", item.getBerthCode()));
        });
        return data;
    }

    @Override
    public void deleteVisa(StatisticsSearchDTO dto) {
        Integer I=statisticsQuery.deleteById(Long.parseLong(dto.getId()));
        if(I==0){
            throw new RuntimeException("删除失败！");
        }
    }

    public List<String> carSearchSpec(String code) {
        List<String> strList = new ArrayList<>();
        if(code!=null) {
            String str2 = code.substring(0, 2);
            String str4 = code.substring(0, 4);
            String str6 = code.substring(0, 6);

            if (str2.equals("08") || str2.equals("03")) {
                strList.add(code);
                strList.add(str2);
            }
            if (str4.equals("1242") || str4.equals("1731")) {
                strList.add(code);
                strList.add(str4);
            }
            if (str6.equals("033001")) {
                strList.add(code);
                strList.add(str6);
            }
        }
        return strList;
    }
    @Override
    public List<TrainComprehensiveStatisticsVO> trainLoading(StatisticsSearchDTO dto) {
        List<TrainComprehensiveStatisticsVO> data=statisticsQuery.trainLoadingQuery(dto);
        TrainComprehensiveStatisticsVO sum = statisticsQuery.sumTrainLoadingQuery(dto);
        List<TrainComprehensiveStatisticsVO> list = new ArrayList<>();
        int cs = 0;
        int ds = 0;
        double sj = 0.0;
        for(int i=0;i<data.size()-1;i++){
            cs=cs+(data.get(i).getCoachCount().intValue());
            ds=ds+(data.get(i).getTotalTon().intValue());
            sj=sj+(data.get(i).getSj().doubleValue());
            list.add(data.get(i));
            if(!data.get(i).getPlanDate().equals(data.get(i+1).getPlanDate()) || i+1==data.size()-1){
                TrainComprehensiveStatisticsVO td=new TrainComprehensiveStatisticsVO();
                td.setTotalTon( BigDecimal.valueOf(ds));
                td.setCargoTypeName("日小计");
                td.setCoachCount(BigDecimal.valueOf(cs));
                td.setSj(BigDecimal.valueOf(sj));
                td.setZd(BigDecimal.valueOf(sj).divide(BigDecimal.valueOf(cs), 1, RoundingMode.HALF_UP));
                list.add(td);
                cs = 0;
                ds = 0;
                sj = 0.0;
            }
        }
        TrainComprehensiveStatisticsVO sumTrain=new TrainComprehensiveStatisticsVO();
        sumTrain.setTotalTon( sum.getSumDs());
        sumTrain.setLoadType("合计");
        sumTrain.setCoachCount(sum.getSumCs());
        sumTrain.setSj(sum.getSumSj());
        sumTrain.setZd(sum.getSumSj().divide(sum.getSumCs(), 1, RoundingMode.HALF_UP));
        list.add(sumTrain);


        return list;
    }

    @Override
    public void trainLoadingExport(HttpServletResponse response, StatisticsSearchDTO dto) {
        List<TrainComprehensiveStatisticsVO> data=statisticsQuery.trainLoadingQuery(dto);
        TrainComprehensiveStatisticsVO sum = statisticsQuery.sumTrainLoadingQuery(dto);
        List<TrainComprehensiveStatisticsVO> list = new ArrayList<>();
        int cs = 0;
        int ds = 0;
        double sj = 0.0;
        for(int i=0;i<data.size()-1;i++){
            cs=cs+(data.get(i).getCoachCount().intValue());
            ds=ds+(data.get(i).getTotalTon().intValue());
            sj=sj+(data.get(i).getSj().doubleValue());
            list.add(data.get(i));
            if(!data.get(i).getPlanDate().equals(data.get(i+1).getPlanDate()) || i+1==data.size()-1){
                TrainComprehensiveStatisticsVO td=new TrainComprehensiveStatisticsVO();
                td.setTotalTon( BigDecimal.valueOf(ds));
                td.setCargoTypeName("日小计");
                td.setCoachCount(BigDecimal.valueOf(cs));
                td.setSj(BigDecimal.valueOf(sj));
                td.setZd(BigDecimal.valueOf(sj).divide(BigDecimal.valueOf(cs), 1, RoundingMode.HALF_UP));
                list.add(td);
                cs = 0;
                ds = 0;
                sj = 0.0;
            }
        }
        for (TrainComprehensiveStatisticsVO record : list) {
            record.setLoadType(DictBizCache.getValue("load_type", record.getLoadType()));
        }
        TrainComprehensiveStatisticsVO sumTrain=new TrainComprehensiveStatisticsVO();
        sumTrain.setTotalTon( sum.getSumDs());
        sumTrain.setLoadType("合计");
        sumTrain.setCoachCount(sum.getSumCs());
        sumTrain.setSj(sum.getSumSj());
        sumTrain.setZd(sum.getSumSj().divide(sum.getSumCs(), 1, RoundingMode.HALF_UP));
        list.add(sumTrain);
        String title = "火车装卸日过录表";
        String fileName = "火车装卸日过录表";
        OfficeExportUtil.exportExcel(OfficeExportUtil.getWorkbook(title, "sheet1", TrainComprehensiveStatisticsVO.class, list), fileName, response);
    }
    @Override
    public void workShiftStatisticsExport(HttpServletResponse response, StatisticsSearchDTO dto) {
        List<TrainShiftStatisticsVO> data = statisticsQuery.TrainShiftStatistics(dto);
        TrainShiftStatisticsVO sum= statisticsQuery.sumTrainShiftStatistics(dto);
        data.add(sum);
        String title = "分班次作业情况表";
        String fileName = "分班次作业情况表";
        Workbook workbook = (OfficeExportUtil.getWorkbook(title, "sheet1", TrainShiftStatisticsVO.class, data));
        Sheet sheet = workbook.getSheetAt(0);
        sheet.addMergedRegion(new CellRangeAddress(2, 3, 26, 26));
        sheet.addMergedRegion(new CellRangeAddress(2, 3, 25, 25));
        OfficeExportUtil.exportExcel(workbook, fileName, response);

    }
    @Override
    public List<TrainShiftStatisticsVO> workShiftStatistics(StatisticsSearchDTO dto) {
        List<TrainShiftStatisticsVO> data = statisticsQuery.TrainShiftStatistics(dto);
        data.add(statisticsQuery.sumTrainShiftStatistics(dto));
         return  data;
    }
    @Override
    public List<TrainComprehensiveStatisticsVO> trainStopTime(StatisticsSearchDTO dto) {
        List<TrainComprehensiveStatisticsVO> data =statisticsQuery.trainStopTimeQuery(dto);
        TrainComprehensiveStatisticsVO sum = statisticsQuery.sumTrainStopTimeQuery(dto);
        data.add(sum);
        return data;
    }

    @Override
    public List<WorkLoadStatisticVO> workLoadStatistic(StatisticsSearchDTO dto) {
        List<WorkLoadStatisticVO> data = statisticsQuery.workLoadStatisticQuery(dto);
        WorkLoadStatisticVO sum = statisticsQuery.sumWorkLoadStatisticQuery(dto);
        data.add(sum);
        return data;
    }

    @Override
    public void workLoadStatisticExport(HttpServletResponse response, StatisticsSearchDTO dto) {
        List<WorkLoadStatisticVO> data = statisticsQuery.workLoadStatisticQuery(dto);
        WorkLoadStatisticVO sum = statisticsQuery.sumWorkLoadStatisticQuery(dto);
        data.add(sum);
        if (sum != null) {
            WorkLoadStatisticVO.Work work = new WorkLoadStatisticVO.Work();
            work.setPlanQuantityS(sum.getWork().get(0).getWorkQuantityS().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            work.setPlanQuantityZ(sum.getWork().get(0).getWorkQuantityZ().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            work.setHjPlan(sum.getWork().get(0).getHjWork().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            List<WorkLoadStatisticVO.Work> works = new ArrayList<>();
            works.add(work);
            WorkLoadStatisticVO.Kt kt = new WorkLoadStatisticVO.Kt();
            kt.setPlanLineCountS(sum.getKt().get(0).getWorkLineCountS().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            kt.setPlanLineCountZ(sum.getKt().get(0).getWorkLineCountZ().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            kt.setHjPlanKt(sum.getKt().get(0).getHjWorkKt().divide(dto.getTimespace(), 0, RoundingMode.HALF_UP));
            List<WorkLoadStatisticVO.Kt> kts = new ArrayList<>();
            kts.add(kt);
            WorkLoadStatisticVO BJ = new WorkLoadStatisticVO();BJ.setPlanDate("日均/班均");BJ.setWork(works);BJ.setKt(kts);
            data.add(BJ);
            WorkLoadStatisticVO rate = new WorkLoadStatisticVO();
            String cashRate = "日作业计划兑现率" +
                    sum.getWork().get(0).getHjWork().divide(sum.getWork().get(0).getHjPlan(), 3, RoundingMode.HALF_UP).multiply(new BigDecimal(100)).setScale(1, RoundingMode.HALF_UP).toString()+"%";
            rate.setPlanDate(cashRate);
            data.add(rate);
        }
        String title = "作业量统计表";
        String fileName = "作业量统计表";
        int hs = data.size();
        Workbook workbook = (OfficeExportUtil.getWorkbook(title, "sheet1", WorkLoadStatisticVO.class, data));
        Sheet sheet = workbook.getSheetAt(0);
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 1, 2));
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 3, 4));
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 5, 6));
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 7, 8));
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 9, 10));
        sheet.addMergedRegion(new CellRangeAddress(hs+2, hs+2, 11, 12));
        sheet.addMergedRegion(new CellRangeAddress(hs+3, hs+3, 0, 12));
        OfficeExportUtil.exportExcel(workbook, fileName, response);
    }
}
